import React, { useEffect, useState } from 'react'
import { NavBar, SwipeCell, Flex, Button, Image, Typography, Stepper, Checkbox, Notify, SubmitBar, Toast } from 'react-vant';
import { useNavigate } from 'react-router-dom'
// 引入接口
import { CartList, remove, updatenum, selectone, selectAll } from '@/api/cart'
// 引入样式
import '@/assert/cart.scss'
type Props = {}

export default function Cart({ }: Props) {
  const navigate = useNavigate()
  const [num, setNum] = useState(0)
  const [list1, setList1] = useState([])//定义购物车列表数据
  const [list2, setList2] = useState([])//定义下方商品列表数据
  const [checked1, setChecked1] = useState(false)  //单条数据选中的状态，默认没有选中
  const [checked2, setChecked2] = useState(true)//全选全不选,默认全选
  let [total, setTotal] = useState(0)//总价钱
  useEffect(() => {
    // 初始化刷新列表
    fn()
  }, [])

  // 购物车数据列表请求
  const fn = () => {
    CartList({ userid: localStorage.getItem('userid') }).then((res) => {
      console.log('购物车列表', res);
      if (res.data.code == '200') {
        setList1(res.data.data) //赋列表数据
        setNum(res.data.data.length) //赋购物车数量
        //********** 实现全选和总和
        // 只要有一个是false，全选的值就是false，否则全选的值就是true
        res.data.data.some((item: any) => { return item.flag == false }) ? setChecked2(false) : setChecked2(true)
        // 遍历每一项，要是该项的flag为true（选中），就计算总和
        res.data.data.forEach((item: any) => {
          if (item.flag) {
            setTotal(total += item.originprice * item.num)
          }
        })
      }
    })
  }
  // 删除某条数据
  const removeFn = (val: string) => {
    console.log('val', val); //
    remove({ cartid: val }).then((res) => {
      console.log('删除数据', res);
      if (res.data.code == '200') {
        // 提示删除成功
        Notify.show({ type: 'success', message: '删除成功' })
        // 刷新列表
        fn()
      }
    })
  }
  // 更新数量
  const changeFn = (val: any, id: any) => {
    console.log('val', val);//val就是数量，件数，+、-、修改值都会出现
    updatenum({ num: val, cartid: id }).then((res) => {
      console.log('更新数量', res);
      if (res.data.code == '200') {
        fn()
      }
    })
  }
  // 更新当前购物车选中的状态    单选和不选某一件商品
  const changeFn2 = (val: boolean, id: string) => {
    console.log('666', val, id);//true或者false 和 cart_14dad907-acfd-4424-99c4-256606e143f6
    selectone({ cartid: id, flag: val }).then((res) => {
      console.log('当前购物车选中的状态 ', res);
      if (res.data.code == '200') {
        fn()
      }
    })
  }

  // 更新所有购物车数据的选中状态
  const selectFn = (val: any) => {
    selectAll({ userid: localStorage.getItem('userid'), type: checked2 }).then((res) => {
      console.log('所有购物车数据的选中状态', res);
      if (res.data.code == '200') {
        fn()
      }
    })

  }
  return (
    <div>
      <NavBar
        title={`购物车(${num})`}
        leftText="返回"
        onClickLeft={() => navigate(-1)}
      />
      {/* 滑动单元格 */}
      <div >
        {list1.map((item: any) => {
          return <SwipeCell rightAction={
            <Button style={{ height: '100%' }} square type="danger" onClick={() => removeFn(item.cartid)}>
              删除
            </Button>
          }
            key={item.cartid}
          >
            <Flex className="demo-product-card" align="stretch">
              {/* 复选框  value就是改变的布尔值 */}
              <Checkbox checked={item.flag} onChange={(value) => changeFn2(value, item.cartid)} />
              <Image src={item.img1} className="demo-product-card__img" />
              <Flex direction="column" justify="between" className="demo-product-card__content">
                <div>
                  <Typography.Title level={5}>{item.proname}</Typography.Title>
                </div>
                <Flex justify="between" align="center">
                  <Typography.Text strong size="lg">
                    ${item.originprice}
                  </Typography.Text>
                  <Typography.Text size="sm" type="secondary">
                    {/* 步进器 */}
                    <Stepper
                      defaultValue={item.num}
                      theme='round'
                      onMinus={() => console.log('minus')}//减-
                      onPlus={() => console.log('plus')} //加+
                      onChange={(e) => changeFn(e, item.cartid)}//直接修改
                    />
                  </Typography.Text>
                </Flex>
              </Flex>
            </Flex>
          </SwipeCell>
        })}
      </div>

      {/*总计:提交订单栏 checked={item.flag} */}
      <SubmitBar price={total} buttonText="提交订单" onSubmit={() => { Toast.info('提交') }} >
        <Checkbox checked={checked2} onChange={(value) => selectFn(value)} />全选
      </SubmitBar>
    </div>
  )
}